<!-- 首页 -->
<template>
	<view class="index">
		<!-- 顶部标题 -->
		<view class="standard" v-if="userInfo.phone">
			<view class="logout" @click="handleLogout(1)">
				<image src="/static/img/u171.svg" mode="" style="width: 36px; height: 36px;" />
				<view style="font-size: 28rpx;">退出登录</view>
			</view>
			<!-- 用户信息区域 -->
			<view class="user-info">
				<view style="margin: 0 auto;">
					<view class="user-avatar">
						<image src="/static/img/logo/login.png" mode=""
							style="width: 60px;height: 60px;border-radius: 20%;" />
					</view>
					<view class="user-detail">
						<text>{{ nickUserInfo.nickName || '微信用户' }} / {{ userInfo.phone || '-' }}</text>
					</view>
				</view>

			</view>
		</view>
		<view class="standard" v-else>
			<view class="logout">
			</view>
			<!-- 用户信息区域 -->
			<view class="user-info">
				<view style="margin: 0 auto;">
					<view class="user-avatar" @click="handleLogout(2)">
						<image style="width: 60px;height: 60px;border-radius: 20%;" :src="getAvatar('登录')" />
					</view>
				</view>

			</view>
		</view>

		<view class="status-tabs">
			<view class="tab-item" :class="{ active: currentTab === 'all' }" @click="switchTab('all')">
				全部({{ listStat.total || 0 }})
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'pending' }" @click="switchTab('pending')">
				待支付({{ listStat.toBePay || 0 }})
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'paid' }" @click="switchTab('paid')">
				已支付({{ listStat.hasPay || 0 }})
			</view>
		</view>
		<!-- 状态标签栏 -->
		<!-- 订单列表 -->
		<view class="order-list">
			<view style="text-align: center;color: red;" v-if="userInfo.phone">
				{{ description.description || '' }}
			</view>
			<view class="order-item" v-for="(item, index) in orderList" :key="index" @click="details(item)">
				<view class="order-header">
					<long-press-tooltip :tooltip-text="item.payee + '/' + item.canteenName"
						class="shop-name text-ellipsis">
						{{ item.payee || '' }}/{{ item.canteenName || '' }}
					</long-press-tooltip>
					<text class="statusBox" :style="{
						color: statusList.find(res => { return res.status == item.payStatus }).color,
					}">
						{{statusList.find(res => { return res.status == item.payStatus }).label}}
					</text>
				</view>
				<view class="order-info">
					<view class="info-row">
						<text class="label">用餐时间：</text>
						<text class="value">{{ item.diningStartTime || '' }}~{{ item.diningEndTime || '' }}</text>
					</view>
					<view class="info-row">
						<text class="label">创建时间：</text>
						<text class="value">{{ item.createTime || '-' }}</text>
					</view>
					<view class="info-row">
						<view style="margin-right:  100rpx; display: flex;">
							<view class="label">用餐金额：</view>
							<!-- <text class="value">¥{{ item.diningAmount || 0 }}</text> -->
							<yuanPrice :value="item.diningAmount" />
						</view>
						<view style="display: flex;">
							<view class="label">其他费用金额：</view>
							<!-- <text class="value">¥{{ item.othersAmount || 0 }}</text> -->
							<yuanPrice :value="item.othersAmount" />
						</view>
					</view>
					<view class="total-row">
						<view style="display: flex; margin-top: 30rpx;">
							<view class="total-label" style="display: flex;align-items: center;">合计：</view>
							<!-- <text class="total-value">¥{{ item.totalAmount || '' }}</text> -->
							<yuanPrice :value="item.totalAmount" />
						</view>
						<view>
							<view class="action-buttons" v-if="item.payStatus == 0">
								<u-button size="mini" @click="cancelPay(item)">取消支付</u-button>
								<u-button size="mini" type="primary" @click="goPay(item)">去支付</u-button>
							</view>
							<!-- //退款状态展示 -->
							<view v-if="item.status == 4 || item.status == 6 || item.status == 7" style="margin-top: 34rpx;">
								<text class="statusBox" :style="{
									color: statusList.find(res => { return res.status == item.status }).color,
								}">
									{{statusList.find(res => { return res.status == item.status }).label}}
								</text>
							</view>

						</view>
					</view>
				</view>
			</view>
			<u-empty v-if="total == 0 && loaStatus == 'nomore'" mode="list" margin-top="200" text="暂无记录哦!" />
			<u-loadmore v-else :status="loaStatus" loadingIcon="semicircle" height="30" line />
		</view>

		<!-- 底部扫码悬浮按钮 -->
		<movable-area class="fixed-box" :style="{ height: `calc(100vh - ${navigationBarHeight}px)` }">
			<movable-view class="fixed-button" direction="all" :inertia="true">
				<u-icon size="54" name="scan" color="#fff" @click="handleScan" />
			</movable-view>
		</movable-area>

		<!-- 提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import {
	getList,
	getCancel,
	getUserByPhone,
	getListNumb,
	getInformation
} from '@/api/meal/home.js'
import pay from '@/utils/pay.js'
import {
	getPayInfo,
} from '@/api/meal/feeDetails'
import {
	paySuccessService
} from '@/api/order/order.js'
import yuanPrice from '@/components/yuanPrice/yuanPrice.vue'
import LongPressTooltip from '@/components/tooltip/tooltip.vue'
export default {
	components: {
		yuanPrice,
		LongPressTooltip
	},
	data() {
		return {
			navigationBarHeight: this.globalData.navigationBarHeight, //总体高度
			currentTab: 'all',
			userInfo: {},
			orderList: [],
			statusList: [{
				label: '待支付',
				status: 0,
				color: '#f5a031'
			}, {
				label: '已支付',
				status: 1,
				color: '#19be6b'
			}, {
				label: '已取消',
				status: 2,
				color: '#c2c2c2'
			},
			{
				label: '退款审核中',
				status: 4,
				color: '#c2c2c2'
			},
			{
				label: '退款通过',
				status: 6,
				color: '#c2c2c2'
			},
			{
				label: '退款驳回',
				status: 7,
				color: '#c2c2c2'
			}
			],
			homeForm: {
				phone: '',
				payStatus: '',
				wxUserId: "",
				pageNum: 1,
				pageSize: 10
			},
			nickUserInfo: {},
			listStat: {},
			description: {},
			total: 0,
			loaStatus: 'loading', // 底部加载更多
		}
	},
	// onload(e){
	// 	this.currentTab = e.pending
	// 	this.getHomeList(true);

	// },
	onShow(e) {
		console.log(e);
		if (e) {
			this.currentTab = e.pending
		}
		this.infutatText()
		this.getUserInfo();
		this.getCounts(); // 获取数量
		this.getHomeList(true);
	},
	/** 页面上拉触底事件的处理函数 */
	onReachBottom() {
		if (this.total > this.homeForm.pageNum * this.homeForm.pageSize) {
			this.homeForm.pageNum++
			this.getHomeList()
		} else {
			this.loaStatus = 'nomore'
		}
	},
	/** 用户下拉刷新 */
	onPullDownRefresh() {
		this.getHomeList(true);
		this.getCounts(); // 获取数量
	},
	methods: {
		/**获取图标 */
		getAvatar(userName) {
			let avatarUrl = ('https://ui-avatars.com/api/?background=2979FF&color=fff&length=2&name=' +
				userName || '-')
			return avatarUrl
		},
		/**获取协议 */
		infutatText() {
			getInformation(2).then((res) => {
				console.log(res);
				if (res.data.code == 200) {
					this.description = res.data.data
				}
			})
		},
		/**获取总计 */
		getCounts() {
			let user = uni.getStorageSync('user')
			// if (userInfo) {
			getListNumb({
				wxUserId: user.id,
				phone: this.userInfo.phone
			}).then((res) => {
				console.log(res);
				if (res.data.code == 200) {
					this.listStat = res.data.data
				}
			})
			// }
		},
		// 获取用户信息
		getUserInfo() {
			const userInfo = uni.getStorageSync('user');
			if (userInfo.phone) {
				this.userInfo = userInfo;
				getUserByPhone(userInfo.phone).then((res) => {
					if (res.data.code == 200) {
						this.nickUserInfo = res.data.data
					}
				})
			}
		},
		/**获取列表 */
		getHomeList(val) {
			if (val) {
				this.homeForm.pageNum = 1
			}
			uni.showLoading({
				title: '加载中...'
			})
			this.loaStatus = 'loading'
			let user = uni.getStorageSync('user')
			this.homeForm.wxUserId = user.id
			this.homeForm.phone = this.userInfo.phone
			getList(this.homeForm).then((res) => {
				uni.hideLoading();
				uni.stopPullDownRefresh()
				if (res.data.code == 200) {
					this.total = res.data.total
					if (val) {
						this.orderList = res.data.rows
					} else {
						this.orderList = this.orderList.concat(res.data.rows)
					}
					if (res.data.total <= 10) {
						this.loaStatus = 'nomore'
					} else {
						this.loaStatus = 'loadmore'
					}
				}
			})
		},
		switchTab(tab) {
			this.currentTab = tab;
			if (tab == 'all') {
				this.homeForm.payStatus = ''
			} else if (tab == 'pending') {
				this.homeForm.payStatus = 0
			} else {
				this.homeForm.payStatus = 1
			}
			this.getHomeList(true)
		},
		handleLogout(e) {
			if (e == 1) {
				uni.showModal({
					title: '提示',
					content: '确认退出登录？',
					success: (res) => {
						if (res.confirm) {
							uni.removeStorageSync('token');
							uni.removeStorageSync('user');
							uni.reLaunch({
								url: '/pages/tabBar/login/login'
							});
						}
					}
				});
			} else {
				uni.reLaunch({
					url: '/pages/tabBar/login/login'
				});
			}
		},
		handleScan() {
			uni.scanCode({
				success: (res) => {
					console.log('扫码结果：', res);
					// 处理扫码结果
					// 路由跳转
					uni.navigateTo({
						url: '/' + res.path
					});
				}
			});
		},
		cancelPay(item) {
			uni.showModal({
				title: '提示',
				content: '是否取消支付？',
				success: (res) => {
					if (res.confirm) {
						getCancel({
							id: item.id
						}).then((res) => {
							if (res.data.code == 200) {
								this.getCounts();
								this.getHomeList(true);
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								});
							}
						})
						// 执行取消支付操作
					}
				}
			});
		},
		/**跳转详情 */
		details(item) {
			uni.navigateTo({
				url: '/pages/meal/feeDetails/feeDetails' + this.$u.queryParams(item)
			});
		},
		async goPay(item) {
			try {
				const res = await getPayInfo({
					id: item.id
				});

				if (res.data.code !== 200) {
					uni.showToast({
						title: res.data.msg || '获取订单失败',
						icon: 'none'
					});
					return;
				}

				const payInfo = res.data.data;
				const orderId = item.id;

				// 发起微信支付
				pay.wxpays(this, payInfo,
					// 支付成功回调
					async (res, param) => {
						try {
							console.log('支付成功回调', orderId);
							const rest = await paySuccessService(orderId);
							if (rest.data.code === 200) {
								uni.showToast({
									title: "支付成功",
									icon: 'success',
									duration: 1000
								});
								uni.redirectTo({
									url: '/pages/tabBar/home/home'
								});
								// this.getHomeList()
							} else {
								uni.redirectTo({
									url: '/pages/tabBar/home/home'
								});
								uni.showToast({
									title: rest.data.msg || '支付成功回调失败',
									icon: 'error',
									duration: 1000
								});
							}
						} catch (err) {
							console.error('支付成功后处理异常:', err);
							this.getHomeList()
						}
					},
					// 支付取消回调
					() => {
						uni.hideLoading();
						this.isSubmit = false;
						uni.showToast({
							title: "取消支付",
							icon: 'none',
							duration: 1000
						});
						uni.redirectTo({
							url: '/pages/tabBar/home/home'
						});
					}
				);
			} catch (error) {
				console.error('goPay 异常:', error);
				uni.showToast({
					title: '支付发起失败',
					icon: 'none'
				});
			}
		},
	}
}
</script>

<style lang="scss">
.text-ellipsis {
	max-width: 400rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.index {
	width: 100vw;
	min-height: 100vh;
	// background: linear-gradient(180deg, #4BB5FF 0%, #6AA1FF 100%);
	// padding-bottom: 120rpx;
}

.header {
	padding: 60rpx 30rpx 20rpx;
	display: flex;
	justify-content: center;
	align-items: center;

	.title {
		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;
	}
}

.standard {
	// height: 480rpx;
	// background-image: url(/static/img/u132.png);
	// background-size: contain; // 或者 cover
	// background-repeat: no-repeat;
	// background-position: center;
	//   position: absolute;
	//    top: 0;
	//    left: 0;
	//    right: 0;
	//    bottom: 0;
	//    z-index: -1;
	//    // background-image: url('/static/bg.png'); /* 你的背景图 */
	//    background-size: cover; /* 或 contain，根据实际情况 */
	//    background-position: top center;
	height: 477rpx;
	padding-top: 40rpx;
	background-image: url(/static/img/u132.png);
	background-size: contain;
	background-repeat: no-repeat;
	background-position: center;
	background-size: cover;
	background-position: top center;
}


.user-info {
	// margin: 20rpx 30rpx;
	// background: rgba(255, 255, 255, 0.2);
	border-radius: 20rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;

	.user-detail {
		flex: 1;
		color: #FFFFFF;
		font-size: 32rpx;
		text-align: center;
	}

}

.logout {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	color: #FFFFFF;
	font-size: 24rpx;
	margin-right: 20rpx;
}

.status-tabs {
	display: flex;
	background: #FFFFFF;
	padding: 20rpx;
	position: sticky;
	top: 0;
	width: 100%;
	z-index: 999;
	border-radius: 20rpx 20rpx 0 0;
	// margin: 0 30rpx;

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666666;
		padding: 10rpx 0;

		&.active {
			color: #4BB5FF;
			font-weight: bold;
		}
	}
}

.user-avatar {
	text-align: center;
}

.order-list {
	// margin: 0 30rpx;
	background: #f5f2f2;
	border-radius: 0 0 20rpx 20rpx;
	padding: 20rpx;

	.order-item {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		// margin: 0 30rpx;

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.shop-name {
				font-size: 28rpx;
				font-weight: bold;
			}

			.order-status {
				font-size: 24rpx;

				&.pending {
					color: #FF9900;
				}

				&.paid {
					color: #4BB5FF;
				}

				&.cancelled {
					color: #999999;
				}
			}
		}

		.info-row {
			display: flex;
			font-size: 24rpx;
			margin-bottom: 10rpx;

			.label {
				color: #333333;
				display: flex;
				align-items: center;

				// width: 190rpx;
			}

			.value {
				color: #333333;
				flex: 1;
			}
		}

		.total-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
			border-top: 4rpx solid #f5f2f2;

			.total-value {
				color: #FF6B00;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.action-buttons {
			display: flex;
			justify-content: flex-end;
			margin-top: 20rpx;
			gap: 20rpx;
		}
	}
}

/* 可移动区域块 */
.fixed-box {
	pointer-events: none; // 这里是重点，盒子可穿透操作
	width: 100vw;
	height: 100vh;
	position: fixed;
	left: 0;
	bottom: 0;
	z-index: 100000;
}

/* 要移动的按钮块 */
.fixed-button {
	pointer-events: auto;
	top: 80vh;
	left: 85vw;
	z-index: 9999;
	width: 110rpx;
	height: 110rpx;
	display: flex;
	border-radius: 50%;
	align-items: center;
	justify-content: center;
	background-color: #4BB5FF;
	box-shadow: 0 1px 5px 2px rgba(75, 181, 255, 0.4);
}

/* 适配iphonex 有底部横条的 */
@supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
	.fixed-box {
		bottom: constant(safe-area-inset-bottom);
		bottom: env(safe-area-inset-bottom);
	}
}

::v-deep .u-size-mini {
	font-size: 26rpx !important;
	height: 64rpx !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}
</style>